﻿/***************************************************************/
/* 选择部门，人员信息，部门数据进行过滤，权限控制，多选没有实现。  */
/* 开发者：王继辉										       */
/* 时间：2013-10-16  									       */
/* 网址：                                                      */
/* 感谢：www.922197.com                                        */
/* 联系：394594745@qq.com                                      */
/***************************************************************/

$(document).ready(function () {
    $("body").append("<div id='DepartmentUser_Panel'  style='position:absolute; z-index:10001;'></div>");
   
    $(document).click(function (event) {
        var element = event.target;
        var emeCls = $(element).attr("bj");
        if (emeCls != "cBj") {
            $("#DepartmentUser_Panel").css("display", "none");
        }
    });
    
    var controls = $(this).find('input');
    controls.each(function () {
        if ($(this).attr("ctrlType") == "DepartmentUser") {
            $(this).DepartmentUser(
            {
                RootID: ''
            });
        }
    });

});


// ----------------------------------------
// 树数据选择器
// ----------------------------------------
(function ($) { 
    $.fn.DepartmentUser = function (options) {
        var defaults = {
            CtrolID: $(this).attr("id"),
            SingleSelect: true,
            divItemSelect: 'div_item_select',
            showDataDivId: "DepartmentUser_Panel",
            Url:"/crm/Customer/AjaxDepartmentUser.aspx"
        };

        //s 单选  m 多选
        var SelectMode = $(this).attr("SelectMode") == "s";
        var Event = $(this).attr("event");
        //s=Single,m=Mult
        if (options) {
            $.extend(defaults, options);
        }

        //初始化控件
        //添加对应样式
        $(this).wrap("<div id=\"Dept_" + defaults.CtrolID + "\" class=\"deptctrl\" style=\"width:" + (this.width() + 20) + "px\"></div>");
        $(this).width(this.width() - 16);
        $("body").append("<div id='div_tree_" + defaults.CtrolID + "' style='position:absolute; z-index:10001;display:none;background-color: #F5FFFA;\"" + (!SelectMode ? "border:1px solid #ccc; bgcolor:#eee;'><div style=\"background-color: #F5FFFA;\"><input type=\"button\" value=\"确定\" id='btn" + defaults.CtrolID + "_OK'/><input type=\"button\" value=\"取消\" btn" + defaults.CtrolID + "_Cancel'/></div>" : "'>") + "<ul id='tree_" + defaults.CtrolID + "' class='ztree' style=\"margin-top:0px;\"></ul><div>");
        $("#div_tree_" + defaults.CtrolID).width(this.width() + 50);
        $("#tree_" + defaults.CtrolID).width(this.width() + 50);
         

        $("#btn" + defaults.CtrolID + "_OK").click(function (event) {
            var sItems = $.fn.zTree.getZTreeObj("tree_" + defaults.CtrolID).getSelectedNodes();
            var _v = "";
            var _t = ""; 
            $.each(sItems, function (i) {
                _v = (_v == "") ? sItems[i].id : (_v + "," + sItems[i].id);
                _t = (_t == "") ? sItems[i].name : (_t + "," + sItems[i].name);
            });
            setValue(_v);
            setText(_t);
            //debugger
            if (Event != "") {
                eval(Event);
            }
        })



        //异步加载树
        var setting = {
            view: {
                showIcon: showIconForTree,
                selectedMulti: !SelectMode
            },
            async: {
                enable: true,
                url: getUrl
            },
            check: {
                enable: false
            },
            data: {
                key: { 
                    key1: "key1",
                    key2: "key2",
                    title: "t"
                },
                simpleData: {
                    enable: true
                }
            },
            view: {
                expandSpeed: ""
            },
            callback: {
                beforeExpand: beforeExpand,
                onAsyncSuccess: onAsyncSuccess,
                onAsyncError: onAsyncError,
                beforeClick: beforeClick,
                onClick: onClick
            }
        }; 
 
    var log, className = "dark";
    function getUrl(treeId, treeNode) {
        var k1 = treeNode.key1;
        var param;
        if (k1 == "dept")
            param = "Action=loadtree&id=" + treeNode.id + "&functionID=" + funcid;
//        if (k1 == "user") {
//            var k2 = treeNode.key2;
//            param = "Action=loadcustom&id=" + treeNode.id + "&CustomUser=" + k2 + "&functionID=" + funcid;
//        }
        return defaults.Url+"?" + param;
    };

   function beforeExpand(treeId, treeNode) {
        if (!treeNode.isAjaxing) {
            startTime = new Date();
            treeNode.times = 1;
            ajaxGetNodes(treeNode, "refresh");
            return true;
        } else {
            alert("正在下载数据中，请稍后展开节点。。。");
            return false;
        }
    };

function onAsyncSuccess(event, treeId, treeNode, msg) {
    if (!msg || msg.length == 0) {
        return;
    }
    var zTree = $.fn.zTree.getZTreeObj("tree_" + defaults.CtrolID),
			totalCount = treeNode.count;
    if (treeNode.children.length < totalCount) {
        setTimeout(function () { ajaxGetNodes(treeNode); }, perTime);
    } else {
        treeNode.icon = "";
        zTree.updateNode(treeNode);
        zTree.selectNode(treeNode.children[0]);
        endTime = new Date();
        className = (className === "dark" ? "" : "dark");
    }
}

function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
    //        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    //        alert("异步获取数据出现异常。");
    //        treeNode.icon = "";
    //        zTree.updateNode(treeNode);
    treeNode.icon = ""; ;
}

function ajaxGetNodes(treeNode, reloadType) {
    var zTree = $.fn.zTree.getZTreeObj("tree_" + defaults.CtrolID);
    if (reloadType == "refresh") {
        treeNode.icon = "/Scripts/JQuery_zTree_v3.3/css/zTreeStyle/img/loading.gif";
        zTree.updateNode(treeNode);
    }
    zTree.reAsyncChildNodes(treeNode, reloadType, true);
}

 
function beforeClick(treeId, treeNode, clickFlag) {
    className = (className === "dark" ? "" : "dark");
    return (treeNode.click != false);
}

function onClick(event, treeId, treeNode, clickFlag) {
$.ajax({
        type: "GET",
        url: defaults.Url,
        data: { Action: "RightCode", functionID: funcid,Type:treeNode.key1,Code:treeNode.id},
        async: false,
        success: function (data) { 
            if (data != undefined && data.Staute == "Success"){
               if (SelectMode) {//单选模式
                    $("#" + defaults.CtrolID).val(treeNode.name);
                    setValue(treeNode.id);
                    setType(treeNode.key1);
                    setText(treeNode.name.split("(")[0]);
                    hide();
                    if (Event != "") {
                        eval(Event);
                    }
                }
                else {
                    setValue(treeNode.id);
                    setType(treeNode.key1);
                    setText(treeNode.name.split("(")[0]);
                }  
            }
            else
            {
               alert(data.Msg);
            }         
        },
        error: function (e) {
            return;
        }
    }
  );  
}

function showIconForTree(treeId, treeNode) {
    return !treeNode.isParent;
};
  
        //----------------初始化树------------------
        var funcid = getPar1("functionID");
        var CtrlID = "", _treeNode = null;
        _CtrlID = "tree_" + defaults.CtrolID; 
        var obj = defaults.CtrolID;
        GetData("InitTree",funcid);

        function GetData(action,funid) {
             $.ajax({
                    type: "GET",
                    url: defaults.Url,
                    data: { Action: "InitTree", functionID: funcid},
                    async: false,
                    success: function (data) { 
                        if (data != undefined && data[0].error != "true")
                         $.fn.zTree.init($("#tree_" + defaults.CtrolID), setting, data);
                         
                    },
                    error: function (e) {
                        return;
                    }
                }
              ); 
        }
           
        //在页面上显示用户选择界面
        function showPanel() {
            var tLeft = $("#" + obj).offset().left;
            var tTop = $("#" + obj).offset().top + 10;
            $("#div_tree_" + defaults.CtrolID).css({ display: "block", left: tLeft, top: tTop });
        }

        $(document).click(function (event) {
            var element = event.target;
            var id = $(element).attr("id");
            if (id == undefined || id == null) {
                hide();
            }
            else if (id.indexOf("tree_" + defaults.CtrolID) < 0) {
                hide();
            }
        });

        //设置选择的值
        function setValue(value) {
            $("#" + defaults.CtrolID).attr("SValue", value);
        }

        function setText(text) {
            $("#" + defaults.CtrolID).attr("SText", text);
            $("#" + defaults.CtrolID).val(text);
        }

        function getValue(value) {
            return $("#" + defaults.CtrolID).attr("SValue");
        }

        function getText(value) {
            return $("#" + defaults.CtrolID).val();
        }

         function setType(value) {
            $("#" + defaults.CtrolID).attr("SType", value);
        }

        function getType(text) {
           return $("#" + defaults.CtrolID).attr("SType");
        }

        $(this).click(function (event) {
            fn(this.value, event);
        });

        //绑定键盘事件
        $(this).keyup(function (event) {
            fn(this.value, event);
        });

        function fn(v, event) {
            if (event.keyCode == 40) {//down
                chageSelect(1);
            }
            else if (event.keyCode == 38) {//up
                chageSelect(-1);
            }
            else if (event.keyCode == 13) {//回车
                item_click($("#" + defaults.showDataDivId + " div[class='" + defaults.divItemSelect + "']"));
            }
            else if (v.length >= 0) {
                //registerInputEvent();
                setTimeout(showPanel, 0);
            }
            else {
                $("#div_tree_" + defaults.CtrolID).slideUp(200);
            }
        }

        function hide() {
            $("#div_tree_" + defaults.CtrolID).css("display", "none");
        } 
    }
})(jQuery);  





